import util

from ConfigParser import ConfigParser, DEFAULTSECT, ParsingError
import re
from StringIO import StringIO
import sys
import os
root_dir = os.path.split(sys.path[0])[0]

cfg_root_dir = os.path.join(root_dir,'cfg')
cnd_root_dir = os.path.join(root_dir,'cnd')
job_root_dir = os.path.join(root_dir,'job')
res_root_dir = os.path.join(root_dir,'res')
log_root_dir = os.path.join(root_dir,'log')
cal_root_dir = os.path.join(root_dir,'cal')
out_root_dir = os.path.join(root_dir,'out')
tag_root_dir = os.path.join(root_dir,'tag')
prof_root_dir = os.path.join(root_dir,'prof')
pkg_root_dir = os.path.join(root_dir,'pkg')
src_root_dir = os.path.join(root_dir,'src')

def get_job_log_path(odate,name):
	import os
	d = os.path.join(log_root_dir,odate)
	if not os.path.exists(d):
		os.makedirs(d)
	p = os.path.join(d,"%(name)s.log"%locals())
	if not os.path.exists(p):
		open(p,"w")
	return p

def get_step_log_dir(odate,name):
	import os
	d = os.path.join(log_root_dir,odate,name)
	if not os.path.exists(d):
		os.makedirs(d)
	return d

def get_day_log_path(odate):
	import os
	d = os.path.join(log_root_dir,odate)
	if not os.path.exists(d):
		os.makedirs(d)
	p = os.path.join(d,"__day__.log"%locals())
	if not os.path.exists(p):
		open(p,"w")
	return p

def get_sch_log_path(date="",create=True):
	import os
	if not date:
		date = sysdate()
	d = os.path.join(log_root_dir)
	if not os.path.exists(d):
		os.makedirs(d)
	p = os.path.join(d,"sch-%(date)s.log"%locals())
	if not os.path.exists(p):
		open(p,"w")
	return p

def get_out_path(odate,name,filename="",remove=True):
	import os
	d = os.path.join(out_root_dir,odate,name)
	if not os.path.exists(d):
		os.makedirs(d)
	p = os.path.join(out_root_dir,odate,name,filename)
	if os.path.exists(p) and remove and filename:
		os.remove(p)
	if filename=="":
		return p[:-1]
	return p

def setup_dirs():
	import os
	for d in [cnd_root_dir,job_root_dir,res_root_dir,log_root_dir,cal_root_dir]:
		if not os.path.exists(d):
			os.makedirs(d)

def get(module,section=None,key=None,default=None):
	path = os.path.join(cfg_root_dir,module+'.ini')
	cp = Parser()
	cp.read(path)
	if not section:
		d = {}
		for s in cp.sections():
			d[s]=dict(cp.items(s))
		return d
	for s in cp.sections():
		if s.lower()==section.lower():
			d = dict(cp.items(s))
			if key:
				return d.get(key,default)
			else:
				return d
	if key:
		return default
	else:
		return {}

def sections(module):
	path = os.path.join(cfg_root_dir,module+'.ini')
	cp = Parser()
	cp.read(path)
	return cp.sections()

def set(module,section,key,value):
	path = os.path.join(cfg_root_dir,module+'.ini')
	cp = Parser()
	cp.read(path)
	if not cp.has_section(section):
		cp.add_section(section)
	cp.set(section,key,value)
	cp.write(open(path,'w'))

def sysdate():
	import time
	return time.strftime("%Y%m%d")

class Parser(ConfigParser):
	def read(self,_path,**kwargs):
		fp=StringIO()
		if os.path.exists(_path):
			for line in open(_path,"r").readlines():
				line = util.template(line,**kwargs)
				fp.write(line)
		fp.seek(0)
		self.readfp(fp)
	def _read(self, fp, fpname):
		"""Parse a sectioned setup file.

		The sections in setup file contains a title line at the top,
		indicated by a name in square brackets (`[]'), plus key/value
		options lines, indicated by `name: value' format lines.
		Continuations are represented by an embedded newline then
		leading whitespace.  Blank lines, lines beginning with a '#',
		and just about everything else are ignored.
		"""
		cursect = None							# None, or a dictionary
		optname = None
		lineno = 0
		e = None								  # None, or an exception
		while True:
			line = fp.readline()
			if not line:
				break
			lineno = lineno + 1
			# comment or blank line?
			if line.strip() == '' or line[0] in '#;':
				continue
			if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
				# no leading whitespace
				continue
			# continuation line?
			if line[0].isspace() and cursect is not None and optname:
				value = line[1:].rstrip() # MACIEK - bylo .strip()
				if value:
					cursect[optname] = "%s\n%s" % (cursect[optname], value)
			# a section header or option header?
			else:
				# is it a section header?
				mo = self.SECTCRE.match(line)
				if mo:
					sectname = mo.group('header')
					if sectname in self._sections:
						cursect = self._sections[sectname]
					elif sectname == DEFAULTSECT:
						cursect = self._defaults
					else:
						cursect = {'__name__': sectname}
						self._sections[sectname] = cursect
					# So sections can't start with a continuation line
					optname = None
				# no section header in the file?
				elif cursect is None:
					raise MissingSectionHeaderError(fpname, lineno, line)
				# an option line?
				else:
					mo = self.OPTCRE.match(line)
					if mo:
						optname, vi, optval = mo.group('option', 'vi', 'value')
						if vi in ('=', ':') and ';' in optval:
							# ';' is a comment delimiter only if it follows
							# a spacing character
							pos = optval.find(';')
							if pos != -1 and optval[pos-1].isspace():
								optval = optval[:pos]
						optval = optval.strip()
						# allow empty values
						if optval == '""':
							optval = ''
						optname = self.optionxform(optname.rstrip())
						cursect[optname] = optval
					else:
						# a non-fatal parsing error occurred.  set up the
						# exception but keep going. the exception will be
						# raised at the end of the file and will contain a
						# list of all bogus lines
						if not e:
							e = ParsingError(fpname)
						e.append(lineno, repr(line))
		# if any parsing errors occurred, raise an exception
		if e:
			raise e

if __name__=="__main__":
	p=Parser()
	p.read(r"Y:\riv_prod\job\xxx_task_b.ini")
	print p.sections()
